import comTitle from "@/views/com/com_title.vue";
import buyingIfor from "./buyingIfor/buyingIfor.vue";
import cropperModal from "@/components/cropper/index.vue";
import { addMallfrontpageconfig, putMallfrontpageconfig, detailMallfrontpageconfig } from "@/api/shop/mallHome/shangChao/list.js";
import { upLoad } from '@/api/shop/upLoad.js'
import store from "@/store";

export default {
    components: {
        comTitle,
        buyingIfor,
        cropperModal
    },
    data() {
        return {
            headers: {
                Authorization: "Bearer " + store.getters.access_token,
            },
            labelWidth: "120px",
            disabled: false,
            ruleForm: {
                skipType: '00',
                sxDate: [],  //领取时间
                graphicPic: ""
            },
            rules: {
                bannerName: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                bannerPic: [
                    { required: true, message: '请上传图片', trigger: 'change' },
                ],
                sxDate: [
                    { required: true, message: '请选择生效日期', trigger: 'change' },
                ],
                skipType: [
                    { required: true, message: '请选择跳转方式', trigger: 'change' },
                ],
                graphicPic: [
                    {
                        required: true,
                        message: "请上传图文页",
                    },
                ],
            },
            imageUrl: "",
            loading: false, //上传
            optionsData: {
                title: "商品图片", //弹框表头
                img: "", //裁切图片地址
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 326, //默认生成截图框宽度
                autoCropHeight: 412, //默认生成截图框高度
                fixedBox: false, //固定截图框大小 不允许改变
                thumbnailName: "衣家生活"
            },
            number: 0,
            fileList: [],
            dialogImageUrl: "", //放大图片
            dialogVisibleImg: false,
            imgUrlList: [],

            rejectedreasonList: [],
            loadingSure: false,

            hideUploadEdit: false

        }
    },
    mounted() {
        if (this.$route.query.id) {
            this.getList()
        }

    },
    methods: {
        getList() {
            detailMallfrontpageconfig({ bannerId: this.$route.query.bannerId, areaType: this.$route.query.areaType, businessType: this.$route.query.businessType }).then(val => {
                this.ruleForm = val.data.data.configDto
                this.$set(this.ruleForm, 'sxDate', [this.ruleForm.begainTime, this.ruleForm.endTime])

                let pic = []            //图片回显
                if (this.ruleForm.bannerPic) {
                    this.hideUploadEdit = true
                    if (this.ruleForm.bannerPic.indexOf(',') > -1) {
                        pic = this.ruleForm.bannerPic.split(',')
                        pic.forEach(item => {
                            this.fileList.push({ url: process.url + item, name: '商品图片' })
                            this.imgUrlList.push({ url: item, name: '商品图片' })
                        })
                    } else {
                        this.fileList.push({ url: process.url + this.ruleForm.bannerPic, name: '商品图片' })
                        this.imgUrlList.push({ url: this.ruleForm.bannerPic, name: '商品图片' })
                    }
                }
                if (this.ruleForm.skipType == '01') {

                    if (val.data.data.goodsList) {
                        this.$nextTick(() => {
                            this.$refs['buyingIfor'].dataList = [{ shopInStockNewAddGoodsDetail: val.data.data.goodsList }]
                        })

                    }
                    this.ruleForm.graphicPic = ""
                } else {
                    this.ruleForm.goodsId = ""
                }
                console.log(5263563, this.ruleForm)
            })
        },
        submitSave() {   //提交并保存
            let obj = {}
            if (this.ruleForm.skipType == '01') {
                this.ruleForm.graphicPic = ""
                obj = { ...this.$refs['buyingIfor'].dataList[0] }
                let goodsIds = []
                obj.shopInStockNewAddGoodsDetail.forEach(item => {
                    goodsIds.push(item.goodsId)
                })
                obj.goodsId = goodsIds.join(',')
            } else {
                obj = {}
                obj.goodsId = ""
            }

            let urlList = [...this.imgUrlList]
            if (urlList.length) {  //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(process.url) > -1) {  //截取路径
                        item.url = item.url.replace(process.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.bannerPic = imgList.join(',')
            }


            if (this.$route.query.areaType) {
                obj.areaType = this.$route.query.areaType
            }


            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.bannerPic) {
                        if (this.ruleForm.skipType == '01') {
                            console.log(obj)
                            if (obj.goodsId) {
                                this.loadingSure = true
                                if (this.ruleForm.id) { //编辑还是修改
                                    putMallfrontpageconfig(Object.assign({ businessType: this.$route.query.businessType }, this.ruleForm, obj)).then(() => {
                                        this.quxiao('ruleForm')
                                    }).catch(() => {
                                        this.loadingSure = false
                                    })
                                } else {
                                    addMallfrontpageconfig(Object.assign({ businessType: this.$route.query.businessType }, this.ruleForm, obj)).then(() => {
                                        this.quxiao('ruleForm')
                                    }).catch(() => {
                                        this.loadingSure = false
                                    })
                                }
                            } else {
                                this.$message.warning('最少选择一种商品')
                            }
                        } else {
                            this.loadingSure = true
                            if (this.ruleForm.id) { //编辑还是修改
                                putMallfrontpageconfig(Object.assign({ businessType: this.$route.query.businessType }, this.ruleForm, obj)).then(() => {
                                    this.quxiao('ruleForm')
                                }).catch(() => {
                                    this.loadingSure = false
                                })
                            } else {
                                addMallfrontpageconfig(Object.assign({ businessType: this.$route.query.businessType }, this.ruleForm, obj)).then(() => {
                                    this.quxiao('ruleForm')
                                }).catch(() => {
                                    this.loadingSure = false
                                })
                            }
                        }

                    } else {
                        this.$message.warning('请上传商品图片')
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        quxiao(ruleForm) {  //取消
            this.$router.go(-1)
            this.$refs[ruleForm].resetFields();
            this.ruleForm = {

            }
            this.loadingSure = false
        },
        addStore() {
            this.$refs.choiceShop.dialogVisibleTile = '添加直送门店'
            this.$refs.choiceShop.dialogVisible = true
        },
        trigger(data) {
            this.$refs.buyingIfor.dataList = []
            data.chioseVal.forEach(i => {
                this.$refs.buyingIfor.dataList.push({   //将门店push 到采购信息中去
                    mendian: i
                })
            });
        },
        handleChange(file, fileList) {
            //上传触发
            // console.log(file)
            let { options } = this;
            // console.log(file)
            // fileBase64(file.file.originFileObj).then(result => {
            let target = Object.assign({}, options, {
                img: file.url,
                files: file
            });
            this.$refs["cropperModal"].edit(target);
            // })
        },
        beforeUpload(file) {
            const isJpgOrPng =
                file.type === "image/jpeg" || file.type === "image/png";
            if (!isJpgOrPng) {
                this.$message.error("图片格式不支持！");
            }
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                this.$message.error("图片大小限制在1MB内!");
            }
            return isJpgOrPng && isLt1M;
        },
        handlePictureCardPreview(file) {
            this.dialogVisible = true;
            this.dialogImageUrl = file.url
        },
        delUplod(file) {
            console.log('delUplod',file)
            this.hideUploadEdit = false
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            this.fileList = newFileList;
            this.imgUrlList.splice(index, 1)
        },

        onSuccess(res, file, fileList){
            var obj = {}
            obj.url  = res.data.url
            obj.name = "image.png"
            this.imgUrlList.push(obj)
            this.fileList.push({
                uid: this.number++,
                name: 'image.png',
                status: 'done',
                url: res.data.url
            })
            this.$message.success('上传成功！')
        },
        onError(){
            this.$message.warning('上传失败，请重新上传！')
        },
        handleCropperSuccess(data) {
            upLoad(data).then(res => {
                this.imgUrlList.push(res.data.data)
                this.fileList.push({
                    uid: this.number++,
                    name: 'image.png',
                    status: 'done',
                    url: URL.createObjectURL(data)
                })
                this.$message.success('上传成功！')
                this.hideUploadEdit = true
            }).catch(() => {
                this.$message.warning('上传失败，请重新上传！')
            })
        },

        sxDateChange(e) {
            console.log(e)
            if (e) {
                this.ruleForm.begainTime = this.formDate(e[0])
                this.ruleForm.endTime = this.formDate(e[1])
            }
            this.$forceUpdate()
        },
        handleAvatarSuccessGraphicPic(res, file) {
            this.ruleForm.graphicPic = res.data.url;
            this.$refs.ruleForm.validateField("graphicPic")
        },
        handleBannerSuccessGraphicPic(res, file) {
            this.ruleForm.bannerPic = res.data.url;
            this.$refs.ruleForm.validateField("bannerPic")
        },
    },

} 